package com.gengzp.common.config;

import com.gengzp.common.interceptor.TraceInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @ClassName WebConfig
 * @Description WebMvcConfigurer配置类
 * @Author gengzp
 * @Date 2025/9/8 14:13
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private TraceInterceptor traceInterceptor;

    /**
     * 跨域处理
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 对所有接口生效
                .allowedOriginPatterns("http://*")
                .allowCredentials(true) // 允许携带Cookie
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的请求方法（必须包含OPTIONS，预检请求会用）
                .allowedHeaders("*") // 允许所有请求头（避免自定义头被拦截）
                .maxAge(3600); // 预检请求缓存时间（1小时，避免频繁预检）
    }

    /**
     * 链路追踪拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(traceInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns( // 日志管理的查询接口不需要拦截
                        "/log/trace/create",
                        "/log/trace/page",
                        "/log/operation/create",
                        "/log/operation/page"
                );
    }

}
